import 'package:flutter_easyrefresh/easy_refresh.dart';

import 'item.dart';
import 'list_mock.dart';
import 'package:flutter/material.dart';

class ListIndex extends StatefulWidget {
  const ListIndex({Key? key}) : super(key: key);

  @override
  _ListIndexState createState() => _ListIndexState();
}

class _ListIndexState extends State<ListIndex> {
  List<Map<String, Object>> _listItems = [];
  int _currentPage = 1;
  static const int PAGE_SIZE = 10;

  void _refresh() {
    _currentPage = 1;
    _requestNewItems();
  }

  void _load() {
    _currentPage += 1;
    _requestNewItems();
  }

  void _requestNewItems() async {
    List<Map<String, Object>> _newItems =
        await listMockData.list(_currentPage, PAGE_SIZE);
    setState(() {
      if (_currentPage > 1) {
        _listItems += _newItems;
      } else {
        _listItems = _newItems;
      }
      print('list $_listItems');
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('A List App1'),
        ),
        body: EasyRefresh(
            firstRefresh: true,
            onRefresh: () async {
              _refresh();
            },
            onLoad: () async {
              _load();
            },
            child: ListView.builder(
                itemCount: _listItems.length,
                itemBuilder: (context, index) {
                  print('render $_listItems');
                  return ListItem(
                    title: _listItems[index]['title'],
                    image: _listItems[index]['image'],
                    viewCount: _listItems[index]['viewCount'],
                  );
                })),
      ),
    );
  }
}
